import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import userApi from '../apis/user';

/**
 * 用户管理相关的hooks
 */
export function useUser() {
  // 角色类型选项
  const roleTypeOptions = [
    { label: '普通员工', value: 1 },
    { label: '部门经理', value: 2 },
    { label: '财务人员', value: 3 },
    { label: '系统管理员', value: 4 }
  ];

  // 部门数据映射
  const departmentMap = {
    1: '技术部',
    2: '市场部',
    3: '财务部',
    4: '人力资源部',
    5: '行政部',
    6: '销售部',
    7: '客服部',
    8: '产品部'
  };

  // 搜索表单
  const searchForm = reactive({
    username: '',
    realName: '',
    roleType: '',
    status: ''
  });

  // 分页数据
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  });

  // 加载状态
  const loading = ref(false);

  // 用户列表数据
  const userList = ref([]);

  // 查看对话框状态
  const viewDialogVisible = ref(false);

  // 新增对话框状态
  const addDialogVisible = ref(false);
  const addFormRef = ref(null);
  
  // 编辑对话框状态
  const editDialogVisible = ref(false);
  const editFormRef = ref(null);
  const currentEditId = ref(null);

  // 新增表单数据
  const addForm = reactive({
    username: '',
    realName: '',
    email: '',
    phone: '',
    departmentId: '',
    roleType: '',
    status: 1
  });

  // 新增表单验证规则
  const addFormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    realName: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入电子邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    departmentId: [
      { required: true, message: '请选择所属部门', trigger: 'change' }
    ],
    roleType: [
      { required: true, message: '请选择角色类型', trigger: 'change' }
    ]
  };

  // 查看表单数据
  const viewForm = reactive({
    username: '',
    realName: '',
    email: '',
    phone: '',
    departmentId: '',
    departmentName: '',
    roleType: '',
    roleName: '',
    status: 1,
    updateTime: null
  });
  
  // 编辑表单数据
  const editForm = reactive({
    realName: '',
    email: '',
    phone: '',
    departmentId: '',
    roleType: '',
    status: 1
  });
  
  // 编辑表单验证规则
  const editFormRules = {
    realName: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入电子邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    departmentId: [
      { required: true, message: '请选择所属部门', trigger: 'change' }
    ],
    roleType: [
      { required: true, message: '请选择角色类型', trigger: 'change' }
    ]
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '-';
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  // 根据角色类型获取角色名称
  const getRoleName = (roleType) => {
    const role = roleTypeOptions.find(r => r.value === roleType);
    return role ? role.label : '';
  };

  // 根据部门ID获取部门名称
  const getDepartmentName = (departmentId) => {
    return departmentMap[departmentId] || '';
  };

  // 加载用户数据
  const loadUsers = async () => {
    loading.value = true;
    try {
      // 调用真实的API
      const response = await userApi.getUsers({
        ...searchForm,
        page: pagination.current,
        pageSize: pagination.size
      });

      // 使用后端返回的数据
      if (response.code === 200 && response.data) {
        userList.value = response.data.records || [];
        pagination.total = response.data.total || 0;
      } else {
        ElMessage.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      ElMessage.error('获取用户列表失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };

  // 搜索处理
  const handleSearch = () => {
    pagination.current = 1; // 重置为第一页
    loadUsers();
  };

  // 重置处理
  const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = '';
    });
    pagination.current = 1;
    loadUsers();
  };

  // 查看用户详情
  const handleView = async (row) => {
    try {
      loading.value = true;
      // 调用真实的API获取详情
      const response = await userApi.getUserById(row.id);
      
      // 根据后端返回结果处理
      if (response.code === 200 && response.data) {
        // 使用后端返回的数据填充查看表单
        Object.assign(viewForm, response.data);
        viewDialogVisible.value = true;
      } else {
        ElMessage.error(response.message || '获取用户详情失败');
      }
    } catch (error) {
      console.error('获取用户详情失败:', error);
      ElMessage.error('获取用户详情失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };

  // 编辑用户
  const handleEdit = async (row) => {
    try {
      loading.value = true;
      // 调用API获取用户详情
      const response = await userApi.getUserById(row.id);
      
      if (response.code === 200 && response.data) {
        // 存储当前编辑的用户ID
        currentEditId.value = row.id;
        // 填充编辑表单数据
        Object.assign(editForm, {
          realName: response.data.realName || '',
          email: response.data.email || '',
          phone: response.data.phone || '',
          departmentId: response.data.departmentId || '',
          roleType: response.data.roleType || '',
          status: response.data.status || 1
        });
        // 打开编辑对话框
        editDialogVisible.value = true;
      } else {
        ElMessage.error(response.message || '获取用户信息失败');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      ElMessage.error('获取用户信息失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };
  
  // 提交编辑表单
  const handleEditSubmit = async () => {
    if (!editFormRef.value || !currentEditId.value) return;
    
    try {
      await editFormRef.value.validate();
      loading.value = true;
      
      // 调用真实的API更新用户
      const response = await userApi.updateUser(currentEditId.value, editForm);
      
      // 根据后端返回结果处理
      if (response.code === 200) {
        // 关闭对话框
        editDialogVisible.value = false;
        // 显示成功消息
        ElMessage.success(response.message || '更新用户成功');
        // 重新加载数据
        loadUsers();
      } else {
        ElMessage.error(response.message || '更新用户失败');
      }
    } catch (error) {
      if (error !== false) { // 不是表单验证失败的错误
        console.error('更新用户失败:', error);
        ElMessage.error('更新用户失败，请稍后重试');
      }
    } finally {
      loading.value = false;
    }
  };

  // 打开新增对话框
  const handleAdd = () => {
    // 重置表单
    if (addFormRef.value) {
      addFormRef.value.resetFields();
    }
    // 重置表单数据
    Object.keys(addForm).forEach(key => {
      addForm[key] = key === 'status' ? 1 : '';
    });
    // 打开对话框
    addDialogVisible.value = true;
  };

  // 提交新增表单
  const handleSubmit = async () => {
    if (!addFormRef.value) return;

    try {
      await addFormRef.value.validate();
      loading.value = true;

      // 调用真实的API
      const response = await userApi.addUser(addForm);

      // 根据后端返回结果处理
      if (response.code === 200) {
        // 关闭对话框
        addDialogVisible.value = false;
        // 显示成功消息
        ElMessage.success('新增用户成功');
        // 重新加载数据
        loadUsers();
      } else {
        ElMessage.error('新增用户失败');
      }
    } catch (error) {
      if (error !== false) { // 不是表单验证失败的错误
        console.error('新增用户失败:', error);
        ElMessage.error('新增用户失败，请稍后重试');
      }
    } finally {
      loading.value = false;
    }
  };

  // 切换用户状态
  const handleToggleStatus = async (row) => {
    loading.value = true;
    try {
      // 计算新状态
      const newStatus = row.status === 1 ? 0 : 1;
      
      // 调用真实的API
      const response = await userApi.updateUserStatus(row.id, newStatus);

      // 根据后端返回结果处理
      if (response.code === 200) {
        // 更新本地数据
        row.status = newStatus;
        ElMessage.success(response.message || (newStatus === 1 ? '启用成功' : '禁用成功'));
        // 重新加载数据以确保数据一致性
        loadUsers();
      } else {
        ElMessage.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('切换状态失败:', error);
      ElMessage.error('操作失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };

  // 分页大小变更
  const handleSizeChange = (size) => {
    pagination.size = size;
    loadUsers();
  };

  // 页码变更
  const handleCurrentChange = (current) => {
    pagination.current = current;
    loadUsers();
  };

  return {
    // 数据
    roleTypeOptions,
    departmentMap,
    searchForm,
    pagination,
    loading,
    userList,
    viewDialogVisible,
    viewForm,
    addDialogVisible,
    addFormRef,
    addForm,
    addFormRules,
    editDialogVisible,
    editFormRef,
    editForm,
    editFormRules,
    
    // 方法
    formatDate,
    getRoleName,
    getDepartmentName,
    loadUsers,
    handleSearch,
    handleReset,
    handleView,
    handleEdit,
    handleEditSubmit,
    handleAdd,
    handleSubmit,
    handleToggleStatus,
    handleSizeChange,
    handleCurrentChange
  };
}